import { ref, onMounted, onBeforeUnmount, onActivated, onDeactivated } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MonitorKeyboard from './monitorKeyboard'
/**
 * 获取软键盘状态
 * @param callShow  键盘弹出时回调
 * @param callHidden 键盘收起时回调
 */
export default function GetKeyboardMixin(callShow?: any, callHidden?: any) {
  const show = ref(false)
  let monitorKeyboard: any = null
  const getKeyboardState = () => {
    if (!monitorKeyboard) {
      monitorKeyboard = new MonitorKeyboard()
    }

    // 监听虚拟键盘弹出事件
    monitorKeyboard.onShow((e: any) => {
      show.value = true
      callShow && callShow(e)
    })

    //监听键盘收起的事件
    monitorKeyboard.onHidden((e: any) => {
      show.value = false
      callHidden && callHidden(e)
    })
    monitorKeyboard.onStart()
  }
  onMounted(() => {
    getKeyboardState()
  })

  onActivated(() => {
    getKeyboardState()
  })

  /* onBeforeUnmount(() => {
    if (monitorKeyboard) {
      monitorKeyboard.onEnd()
      monitorKeyboard = null
    }
  }) */
  onBeforeRouteLeave(() => {
    if (monitorKeyboard) {
      monitorKeyboard.onEnd()
      monitorKeyboard = null
    }
  })

  onDeactivated(() => {
    if (monitorKeyboard) {
      monitorKeyboard.onEnd()
      monitorKeyboard = null
    }
  })

  return {
    show
  }
}
